package vmcs.entity;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import vmcs.utility.ReflectionUtils;

// Copyright 1997 ISS.
// The contents contained in this document may not be reproduced in any
// form or by any means, without the written permission of ISS, other
// than for the purpose for which it has been supplied.
//
// Author: Olivo Miotto
//

public class StoreObject implements Cloneable{

    private String name;

    public StoreObject(){}

    public StoreObject(String n){
      name = n;
    }

    public String getName (){
      return name;
    }

    public void setName(String n){
      name = n;
    }

    public void initialize(Map<String, String> params){

    	ArrayList<Field> fieldsList=new ArrayList<Field>();
    	addDeclaredAndInheritedFields(this.getClass(), fieldsList);
    	
		for (Field field : fieldsList) {
			
			field.setAccessible(true);
			
			if (params.get(field.getName())==null){
				continue;
			}
			try {

				 if (field.getType() == boolean.class) {
					 
					field.setBoolean(this, new Boolean(params.get(field.getName())));
					
				} else if (field.getType() == int.class) {
					
					field.setInt(this,Integer.parseInt(params.get(field.getName())));
					
				} else if (field.getType() == double.class) {
					field.setDouble(this,Double.parseDouble(params.get(field.getName() )));
					
				} else {
					field.set(this,params.get(field.getName()));
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("Unable to map field : " + field.getName());
				e.printStackTrace();
			}
		}
    	
    }
    
    
    private static void addDeclaredAndInheritedFields(Class c, List<Field> fields) {
    	
        fields.addAll(Arrays.asList(c.getDeclaredFields())); 
        Class superClass = c.getSuperclass(); 
        if (superClass != null) { 
            addDeclaredAndInheritedFields(superClass, fields); 
        }       
    }
    
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
    @Override
    public String toString() {
    	return ReflectionUtils.toString(this);
    }
}